import common from "@common/api/common";
import GlobalDialog from "@common/components/dialog/global";
import DynamicForm from "@common/components/form/Dynamic";
import { genFormConfig } from "@common/components/form/Dynamic/util";

const genButtons = dialogOpt => {
	let buttons = [];
	buttons.push({
		text: '关 闭',
		click(dialog) {
			dialog.visible = false;
		},
	});
	if (!dialogOpt.disabled) {
		buttons.push({
			type: 'primary',
			text: '确 定',
			click(dialog, { component }) {
				component.validateDynamicForm().then(valid => {
					if (valid) {
						return saveMethod(component, dialogOpt);
					}
					return valid;
				}).then(valid => {
					if (valid) {
						dialog.visible = false;
					}
				});
			}
		});
	}
	return buttons;
};
const saveMethod = (component, dialogOpt) => {
	if (typeof dialogOpt.confirm === 'function') {
		return dialogOpt.confirm(component.formData, component);
	}
	let subData = $.extend({}, component.formData);
	return common.requestData(dialogOpt.url, subData).then(result => {
		typeof dialogOpt.confirmed === 'function' && dialogOpt.confirmed(component, result);
		return true;
	}).catch(() => {
		return false;
	});
}
const FormDialog = (store, router) => {
	let dialog = GlobalDialog(store, router);
	return async dialogOpt => {
		return dialog({
			title: dialogOpt.title,
			width: dialogOpt.width,
			component: {
				value: DynamicForm,
				props: {
					formConfig: genFormConfig(dialogOpt.formConfig),
					data: dialogOpt.data,
					formEvent: dialogOpt.formEvent,
					disabled: dialogOpt.disabled,
				},
			},
			buttons: genButtons(dialogOpt),
		});
	};
};
export default FormDialog;